package com.google.code.sip.ucenter.imports;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.encoding.PasswordEncoder;
import org.springframework.stereotype.Service;

import com.google.code.sip.ucenter.dao.*;
import com.google.code.sip.ucenter.model.User;

@Service("userImporter")
public class UserImporter extends AbstractImporter<User> {
	@Autowired
	private UserDao userDao;
	@Autowired
	private RoleDao roleDao;
	@Autowired
	private UserProfileDao userProfileDao;
	@Autowired
	private UserCustomProfileDao userCustomProfileDao;
	@Autowired
	private UserCountDao userCountDao;
	@Autowired
	private UserEventDao userEventDao;
	@Autowired
	private CreditDao creditDao;
	@Autowired
	private CreditLogDao creditLogDao;
	@Autowired
	private CreditRuleLogDao creditRuleLogDao;
	@Autowired
	private AccountDao accountDao;
	@Autowired
	private AccountLogDao accountLogDao;
	@Autowired
	private AccountDao huoshowAccountDao;
	@Autowired
	private AccountLogDao huoshowAccountLogDao;
	@Autowired
	private FriendDao friendDao;
	@Autowired
	private FriendGroupDao friendGroupDao;

	@Autowired
	private PasswordEncoder passwordEncoder;

	@Override
	protected void doInit() {
		userDao.clear();
		// 清理用户相关数据
		userProfileDao.clear();
		userCustomProfileDao.clear();
		userCountDao.clear();
		userEventDao.clear();
		friendDao.clear();
		friendGroupDao.clear();
		creditDao.clear();
		creditLogDao.clear();
		creditRuleLogDao.clear();
		accountDao.clear();
		accountLogDao.clear();
		huoshowAccountDao.clear();
		huoshowAccountLogDao.clear();
	}

	@Override
	protected User toEntity(Map<String, String> props) {
		User user = new User();
		for (Map.Entry<String, String> entry : props.entrySet()) {
			String name = entry.getKey();
			String value = entry.getValue();
			if (name.equals("password")) {
				user.setPassword(encodePassword(value));
			} else if (name.equals("role")) {
				user.setRole(roleDao.getByName(value));
			} else {
				try {
					if (entityClass.getDeclaredField(name) != null) {
						beanUtilsBean.copyProperty(user, name, value);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		return user;
	}

	@Override
	protected void doSave(User user) {
		// userDao.save(user);
	}

	private String encodePassword(String password) {
		return passwordEncoder.encodePassword(password, null);
	}
}
